package g_phoenixLimiter

import (
	"strconv"
	"sync"
	"testing"
	"time"
)

func BenchmarkLimiter(b *testing.B) {
	limiter := NewEnhancedPhoenixLimiter(PhoenixLimiterConfig{
		Enable:            true,
		PermitsPerSecond:  2,
		BlackListCount:    1,
		BlacklistDuration: 30 * time.Second,
		RecordDuration:    30 * time.Second,
	})
	defer limiter.Close()

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			key := "192.168.1." + strconv.Itoa(i%10)
			limiter.Check(key)
			i++
		}
	})
}

func BenchmarkConcurrentAccess(b *testing.B) {
	limiter := NewEnhancedPhoenixLimiter(PhoenixLimiterConfig{
		Enable:            true,
		PermitsPerSecond:  2,
		BlackListCount:    1,
		BlacklistDuration: 30 * time.Second,
		RecordDuration:    30 * time.Second,
	})
	defer limiter.Close()

	var wg sync.WaitGroup
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			key := "10.0.0." + strconv.Itoa(id%100)
			limiter.Check(key)
		}(i)
	}
	wg.Wait()
}

func BenchmarkBlacklistOperations(b *testing.B) {
	limiter := NewEnhancedPhoenixLimiter(PhoenixLimiterConfig{
		Enable:            true,
		PermitsPerSecond:  2,
		BlackListCount:    1,
		BlacklistDuration: 30 * time.Second,
		RecordDuration:    30 * time.Second,
	})
	defer limiter.Close()

	// 预先添加到黑名单
	limiter.Check("blacklisted_ip")
	limiter.Check("blacklisted_ip")
	limiter.Check("blacklisted_ip")

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			limiter.Check("blacklisted_ip")
		}
	})
}
